//
//  UPSchemeManager.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/24.
//

#import "UPSchemeManager.h"

// 定义枚举值
SchemeJumpType const SchemeJumpTypeMain = @"habapplyic";
SchemeJumpType const SchemeJumpTypeLogin = @"dogmative";
SchemeJumpType const SchemeJumpTypeOrder = @"togetheror";
SchemeJumpType const SchemeJumpTypeContinuing = @"lubricance";

@interface UPSchemeManager ()

@end

@implementation UPSchemeManager

+ (instancetype)shared {
    static UPSchemeManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[UPSchemeManager alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _scheme = @"testity://rexia.sparsoon.habitation/lubricance";
        _tabKey = @"andform";
        _productIdKey = @"collegefold";
    }
    return self;
}

- (void)parser:(NSString *)url {
    NSURL *nsurl = [NSURL URLWithString:url];
    if (!nsurl) return;
    
    NSString *lastPath = [nsurl lastPathComponent];
    NSURLComponents *components = [NSURLComponents componentsWithURL:nsurl resolvingAgainstBaseURL:NO];
    UIViewController *topVC = [UIApplication up_currentViewController];
    
    if (!lastPath || !components || !topVC) return;
    
    if ([lastPath isEqualToString:SchemeJumpTypeMain]) {
        [topVC.navigationController popToRootViewControllerAnimated:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            UIViewController *rootVC = [UIApplication up_currentKeyWindow].rootViewController;
            if ([rootVC isKindOfClass:[UPTabBarViewController class]]) {
                UPTabBarViewController *mainVC = (UPTabBarViewController *)rootVC;
                [mainVC changeViewControllerToIndex:0];
            }
        });
    }
    else if ([lastPath isEqualToString:SchemeJumpTypeLogin]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kLogOutOrExpiredNotificationKey object:nil];
    }
    else if ([lastPath isEqualToString:SchemeJumpTypeOrder]) {
        [topVC.navigationController popToRootViewControllerAnimated:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            UPMyLoanHistoryViewController *historyVC = [[UPMyLoanHistoryViewController alloc] init];
            [topVC.navigationController pushViewController:historyVC animated:YES];
        });
    }
    else if ([lastPath isEqualToString:SchemeJumpTypeContinuing]) {
        if ([topVC isKindOfClass:[UPGoToApplyViewController class]]) {
            return;
        }
        UPGoToApplyViewController *applyVC = [[UPGoToApplyViewController alloc] init];
        NSDictionary *parameters = [self parametersWithQueryItems:components.queryItems];
        if (parameters) {
            NSString *productId = parameters[self.productIdKey];
            if ([productId isKindOfClass:[NSString class]]) {
                applyVC.productId = (NSNumber *)productId;
            }
        }
        [topVC.navigationController pushViewController:applyVC animated:YES];
    }
}

- (NSDictionary<NSString *, id> *)parametersWithQueryItems:(NSArray<NSURLQueryItem *> *)queryItems {
    if (!queryItems || queryItems.count == 0) {
        return nil;
    }
    
    NSMutableDictionary<NSString *, id> *result = [NSMutableDictionary dictionary];
    
    for (NSURLQueryItem *item in queryItems) {
        NSString *name = item.name;
        NSString *value = item.value;
        
        // 处理多值参数（相同key的情况）
        id existingValue = result[name];
        if (existingValue) {
            if ([existingValue isKindOfClass:[NSArray class]]) {
                NSMutableArray *values = [existingValue mutableCopy];
                if (value) {
                    [values addObject:value];
                }
                result[name] = values;
            } else if ([existingValue isKindOfClass:[NSString class]]) {
                NSString *singleValue = existingValue;
                if (value) {
                    result[name] = @[singleValue, value];
                } else {
                    result[name] = @[singleValue];
                }
            }
        } else {
            result[name] = value ?: [NSNull null];
        }
    }
    
    return [result copy];
}

@end
